package com.think.grpcserver

import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ScrollView
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.core.widget.NestedScrollView

class ServerActivity : AppCompatActivity() {
    val mHandler by lazy {
        Handler(Looper.getMainLooper())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_server)
        LogUtil.d("onCreate")
        val request = findViewById<TextView>(R.id.request)
        val callResponse = object :CallResponse{
            override fun onBlock(data: String) {
                mHandler.post {
                    val lastText = request.text
                    request.text = "${lastText} \n ${data}"
                    mHandler.postDelayed({
                        findViewById<NestedScrollView>(R.id.scrollView).fullScroll(ScrollView.FOCUS_DOWN)
                    }, 100)
                }
            }
        }

        clickView(R.id.clear) {
            request.text = ""
        }


        Server.init(callResponse)

        clickView(R.id.start) {
            Server.start()
        }

        clickView(R.id.stop){
            Server.stop()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LogUtil.d("Destory")
    }


}


object LogUtil {
    fun d(tag: String, info: String?) {
        Log.d("guoyh_Grpc_${tag}", "[-${info}-]")
    }

    fun d(info: String) {
        Log.d("guoyh_Grpc_Server", info)
    }
}


fun Activity.clickView(@IdRes id: Int, it: (View) -> Unit) {
    findViewById<View>(id).click(it)
}

fun View.click(it: (View) -> Unit) {
    setOnClickListener(it)
}
interface CallResponse {
    fun onBlock(data: String)
}